package com.vtb.thread;

import java.util.concurrent.BlockingQueue;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.tencent.weibo.api.Statuses_API;
import com.tencent.weibo.utils.WeiBoConst;
import com.vtb.base.VtbBaseReadThread;
import com.vtb.entity.Config;
import com.vtb.entity.DataCache;
import com.vtb.entity.QqOauth;
import com.vtb.entity.RrOauth;
import com.vtb.entity.SsOauth;
import com.vtb.entity.Var;
import com.vtb.servlet.WtbException;
import com.vtb.utils.MessageUtils;

/**
 * 腾讯微博读线程
 *
 * @author Chen Tao
 * @date 2012-7-2 下午5:41:53
 */
public class QqReadThread extends VtbBaseReadThread{
	private static final Log log = LogFactory.getLog(QqReadThread.class);
	private Statuses_API statuses_API = new Statuses_API();  
	private String broadcast_str = null;								//返回的时间线内容字符串
	private JSONObject broadcast_json_data;								//json_data
	private JSONObject broadcast_json;									//获取第一条微博
	private JSONArray images;											//图片地址数组
    public QqReadThread(BlockingQueue<Object> send_queue, BlockingQueue<QqOauth> traver_qqQueue) {
		this.send_queue = send_queue;
		this.traver_qqQueue = traver_qqQueue;
	}
	public void run() {
		log.info(Thread.currentThread().getName()+"已启动");
		while (true) {
			log.debug("*********"+Thread.currentThread().getName()+"在工作！*************");
			try {
				qqOauth = traver_qqQueue.take();
				//初始化API请求参数
				oauth.setOauth_token(qqOauth.getOauth_token());
				oauth.setOauth_token_secret(qqOauth.getOauth_token_secrete());
				broadcast_str = statuses_API.broadcast_timeline(oauth, WeiBoConst.ResultType.ResultType_Json, "0", "0", "2", "0", "1", "0", "0");
			} catch (Exception e) {
				log.error("获取时间线失败：", e);
				throw new WtbException("获取时间线失败", e);
			}
			if (broadcast_str != null) {
				praseResult(broadcast_str);
			}
		}
	}
	/**
	 * 解析返回的字符串
	 *
	 * @param resultString
	 * @author Chen Tao
	 * @date 2012-7-2 下午5:41:24
	 */
	private void praseResult(String resultString){
		broadcast_json_data = (JSONObject) JSONObject.fromObject(resultString).getJSONObject("data");
		if (broadcast_json_data.toString().equals("null")) {
			return;
		}
		broadcast_json = (JSONObject) broadcast_json_data.getJSONArray("info").get(0);
		log.debug("微博:"+broadcast_json);
	    statusTime = broadcast_json.getString("timestamp");
	    source = broadcast_json.getString("from");
	    if (judgeSource(Config.QQ_FROM)) {
            return;
        }
	    lastTime = DataCache.qqlastTime.get(qqOauth.getUni()); 
		if (Long.valueOf(statusTime) > Long.valueOf(lastTime) ) {
			putToQueue(broadcast_json);
		}
	}
	
	/**
	 * 生成人人和新浪微博发送队列
	 *
	 * @param data
	 * @author Chen Tao
	 * @date 2012-7-1 下午08:42:26
	 */
    private void putToQueue(JSONObject data) {
		clone_mapr = DataCache.synCloneMap(RrOauth.class);
		clone_maps = DataCache.synCloneMap(SsOauth.class);

		RrOauth rrOauth = (RrOauth) clone_mapr.get(qqOauth.getRefr());
		SsOauth ssOauth = (SsOauth) clone_maps.get(qqOauth.getRefs());
		if (rrOauth == null && ssOauth == null) {
            return;
        }
		// 如果为@某人的微博  以“~”结尾 不转发
		message = data.getString("origtext");
		if (MessageUtils.cotainString(message, "@,分享,#") || MessageUtils.lastIndex(message, "~")) {
			return;
		}
		//表情过滤后为空 不转发
		message = MessageUtils.qq2rrExpression(message);
		if (message == null || "".equals(message)) {
			return;
		}
		//带视频或音乐的微博 不转发
		if (!data.get("music").toString().equals("null") || !data.get("video").toString().equals("null")) {
			return;
		}
		//带图片的微博 处理
		if (!data.get("image").toString().equals("null")) {
			if (!data.getJSONArray("image").isEmpty()) {
				images = data.getJSONArray("image");
				image_url = images.get(0)+"/2000.jpg";
			}
		}
		try {
		    if (rrOauth != null) {
		        if (qqOauth.getQ2r().equals(Var.OPEN)) {
		            rrOauth.setMessage(message);
	                rrOauth.setImageUrl(image_url);
	                send_queue.put(rrOauth);
	                log.debug("已加入人人发送队列");
                }
	        }
		    if (ssOauth != null) {
		        if (qqOauth.getQ2s().equals(Var.OPEN)) {
		            ssOauth.setMessage(message);
	                ssOauth.setImageUrl(image_url);
	                send_queue.put(ssOauth);
	                log.debug("已加入新浪微博发送队列");
                }
	        }
        } catch (Exception e) {
            log.error("放入人人或新浪微博发送队列失败：", e);
            throw new WtbException("放入人人或新浪微博发送队列失败", e);
        }
	
	}
	
}
